
import pandas as pd
import numpy as np
import os
import cv2

print(cv2.__version__)
#opencv要求路径中不能有中文字符

# 获得图片路径
source_path = r"F:\Tmp\archive\shapes\squares\drawing(81).png"

# img表示输入的图片，即为需要进行形状判断的图片
frame = cv2.imread(source_path)
h, w, ch = frame.shape
result = np.zeros((h, w, ch), dtype=np.uint8)
# 二值化图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
#cv2.imshow("input image", frame)
#print(cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE))
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in range(len(contours)):
    # 提取与绘制轮廓
    cv2.drawContours(result, contours, cnt, (0, 255, 0), 2)
    # 轮廓逼近
    epsilon = 0.05 * cv2.arcLength(contours[cnt], True)
    approx = cv2.approxPolyDP(contours[cnt], epsilon, True)
    #print(approx)
    # 分析几何形状
    corners = len(approx)
    print(corners)
    shape_type = ""
    if corners == 3:
        shape_type = "三角形"
        print(shape_type)
    if corners == 4:
        shape_type = "矩形"
        print(shape_type)
    if corners > 4:
        shape_type = "圆形"
        print(shape_type)
